package com.ruoyi.business.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.business.domain.IdentityResult;
import com.ruoyi.business.domain.TbCompany;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.TbCpadUserMapper;
import com.ruoyi.business.domain.TbCpadUser;
import com.ruoyi.business.service.ITbCpadUserService;

/**
 * 业务用户Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-29
 */
@Slf4j
@Service
public class TbCpadUserServiceImpl implements ITbCpadUserService
{
    @Autowired
    private TbCpadUserMapper tbCpadUserMapper;

    /**
     * 查询业务用户
     *
     * @param id 业务用户主键
     * @return 业务用户
     */
    @Override
    public TbCpadUser selectTbCpadUserById(Long id)
    {
        return tbCpadUserMapper.selectTbCpadUserById(id);
    }

    /**
     * 查询业务用户列表
     *
     * @param tbCpadUser 业务用户
     * @return 业务用户
     */
    @Override
    public List<TbCpadUser> selectTbCpadUserList(TbCpadUser tbCpadUser)
    {
        return tbCpadUserMapper.selectTbCpadUserList(tbCpadUser);
    }

    /**
     * 新增业务用户
     *
     * @param tbCpadUser 业务用户
     * @return 结果
     */
    @Override
    public int insertTbCpadUser(TbCpadUser tbCpadUser)
    {
        tbCpadUser.setCreateTime(DateUtils.getNowDate());
        return tbCpadUserMapper.insertTbCpadUser(tbCpadUser);
    }

    /**
     * 修改业务用户
     *
     * @param tbCpadUser 业务用户
     * @return 结果
     */
    @Override
    public int updateTbCpadUser(TbCpadUser tbCpadUser)
    {
        tbCpadUser.setUpdateTime(DateUtils.getNowDate());
        return tbCpadUserMapper.updateTbCpadUser(tbCpadUser);
    }

    /**
     * 批量删除业务用户
     *
     * @param ids 需要删除的业务用户主键
     * @return 结果
     */
    @Override
    public int deleteTbCpadUserByIds(Long[] ids)
    {
        return tbCpadUserMapper.deleteTbCpadUserByIds(ids);
    }

    /**
     * 删除业务用户信息
     *
     * @param id 业务用户主键
     * @return 结果
     */
    @Override
    public int deleteTbCpadUserById(Long id)
    {
        return tbCpadUserMapper.deleteTbCpadUserById(id);
    }

    /**
     * 校验用户状态
     * @param id
     * @return
     */
    @Override
    public IdentityResult checkUserIdentity(Long id){
        TbCpadUser tbCpadUser = this.selectTbCpadUserById(id);
        if (tbCpadUser==null){
            throw new ServiceException("用户不存在");
        }
        String apiUrl = "https://cpadis.cpad.gov.cn:1443/cpad_par/app/poorHouse/checkIdentity";
        Map<String, Object> params = new HashMap<>();
        params.put("name", tbCpadUser.getUserName());
        params.put("idCode", tbCpadUser.getIdcard());

        String resData = HttpUtil.post(apiUrl, params);
        IdentityResult result = null;
        if (StringUtils.hasText(resData)){
            result = JSON.parseObject(resData, IdentityResult.class);
            tbCpadUser.setStatus(result.getData()?1:2);
            tbCpadUserMapper.updateTbCpadUser(tbCpadUser);
        }
        return result;
    }


    /**
     * 校验用户状态
     * @param tbCpadUser
     * @return
     */
    private IdentityResult checkUserIdentity(TbCpadUser tbCpadUser){
        if (tbCpadUser==null){
            throw new ServiceException("用户不存在");
        }
        String apiUrl = "https://cpadis.cpad.gov.cn:1443/cpad_par/app/poorHouse/checkIdentity";
        Map<String, Object> params = new HashMap<>();
        params.put("name", tbCpadUser.getUserName());
        params.put("idCode", tbCpadUser.getIdcard());

        String resData = HttpUtil.post(apiUrl, params);
        IdentityResult result = null;
        if (StringUtils.hasText(resData)){
            result = JSON.parseObject(resData, IdentityResult.class);
        }
        return result;
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<TbCpadUser> userList, Boolean isUpdateSupport, String operName, TbCompany company)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TbCpadUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                TbCpadUser u = tbCpadUserMapper.selectTbCpadUserByIdcard(user.getIdcard(), company.getId());
                if (StringUtils.isNull(u))
                {
                    user.setCreateTime(new Date());
                    user.setCreateBy(operName);
                    user.setUpdateBy(operName);
                    user.setUpdateTime(new Date());
                    user.setCompanyId(company.getId());
                    user.setCompanyName(company.getName());
                    user.setVerifyStatus(1);

                    //校验用户状态
                    IdentityResult result = this.checkUserIdentity(user);
                    if (result!=null){
                        user.setIsPass(result.getData()?1:0);
                    }
                    tbCpadUserMapper.insertTbCpadUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setId(u.getId());
                    user.setUpdateTime(new Date());
                    user.setUpdateBy(operName);
                    user.setVerifyStatus(1);

                    //校验用户状态
                    IdentityResult result = this.checkUserIdentity(user);
                    if (result!=null){
                        user.setIsPass(result.getData()?1:0);
                    }
                    tbCpadUserMapper.updateTbCpadUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
